import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type {
  TaskTypeEnumType,
  TaskStateEnumType
} from '~/store/monitorManagement/loopMonitorBox/typings'
import type { LoopSwitchGroupDataItemType } from '../loopSwitchGroup/typings'
import type { SwitchLightStrategyDataItemType, SwitchLightStrategyStateType } from './typings'
import { defineComponent, ref, reactive, nextTick, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElSpace,
  ElLink,
  ElButton,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElMessageBox,
  ElMessage
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import AliIcon from '~/components/AliIocn'
import ProSaasTable from '~/components/ProSaasTable'
import ColorfulBadge from '~/components/ColorfulBadge'
import WeeklyTasksComponent from '../../components/switchLightStrategyComponents/WeeklyTasksComponent'
import AllDayTasksModal from '../../components/switchLightStrategyComponents/AllDayTasksModal'
import DeviceApplicationComponent from '../../components/switchLightStrategyComponents/DeviceApplicationComponent'
import TaskScheduleModal from '../../components/switchLightStrategyComponents/TaskScheduleModal'
import useVuexGetters from '~/hooks/useVuexGetters'
import { handleTrim } from '~/utils/util'

export default defineComponent(function SwitchLightStrategy() {
  const store = useStore()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<SwitchLightStrategyDataItemType>({})
  const state = reactive<SwitchLightStrategyStateType>({})
  const userState = useVuexGetters('user', ['permission'])
  const loopSwitchGroupState = useVuexGetters('loopSwitchGroup', ['taskGroupHardwareSelectList'])
  const switchLightStrategyState = useVuexGetters('switchLightStrategy', [
    'taskTypeSelectList',
    'taskTypeEnum',
    'taskStateSelectList',
    'taskStateEnum'
  ])

  // 按回车搜索列表
  const handleKeyDownEnterSearchList = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') nextTick(proSaasTableRef.value!?.toSearch)
  }

  // 根据变更查询列表数据
  const handleChangeValueActionSearchList = () => {
    nextTick(proSaasTableRef.value!?.toSearch)
  }

  // 根据传入参数判断展示何种类型弹框并设置值
  const handleSetVisibleData = (
    visibleType: SwitchLightStrategyStateType['visibleType'],
    record?: SwitchLightStrategyStateType['record']
  ) => {
    state.visible = true
    state.visibleType = visibleType
    state.record = record || {}
  }

  // 清空visible相关数据并查询列表
  const handleClearVisibleData = () => {
    state.visible = undefined
    state.visibleType = undefined
    state.record = undefined
    handleChangeValueActionSearchList()
  }

  // 删除回路分组
  const handleDeleteSelectData = (record?: SwitchLightStrategyDataItemType) => {
    ElMessageBox({
      title: '确认提示',
      message: '确认删除任务？',
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        const res = await store.dispatch('switchLightStrategy/DeleteMonitoSwitchLightTaskInfo', {
          ids: record?.id
        })
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          handleChangeValueActionSearchList()
        }
      })
      .catch(() => {})
  }

  onMounted(() => {
    if (!switchLightStrategyState.taskTypeSelectList.value?.length) {
      store.dispatch('switchLightStrategy/GetTaskTypeSelectList')
    }
    if (!switchLightStrategyState.taskStateSelectList.value?.length) {
      store.dispatch('switchLightStrategy/GetTaskStateSelectList')
    }
    store.dispatch('loopSwitchGroup/GetTaskGroupHardwareList')
  })

  const columns: TableColumnProps<SwitchLightStrategyDataItemType>[] = [
    {
      label: '任务名称',
      prop: 'taskName',
      minWidth: 180,
      fixed: 'left',
      unFixed: true,
      disabled: true,
      showOverflowTooltip: true
    },
    {
      label: '任务模式',
      prop: 'taskType',
      minWidth: 180,
      enumValues: switchLightStrategyState.taskTypeEnum,
      sortable: true
    },
    {
      label: '生效状态',
      prop: 'state',
      minWidth: 180,
      enumValues: switchLightStrategyState.taskStateEnum,
      sortable: true,
      render: (option, value) => (
        <ColorfulBadge
          value={value}
          enumKey={option.row.state!}
          options={{ danger: 2, warning: 0, success: 1 }}
        />
      )
    },
    {
      label: '有效周期',
      prop: 'taskTrem',
      minWidth: 370,
      hidden: true,
      showOverflowTooltip: true,
      render: ({ row }) =>
        !row?.taskTrem ? (
          <>
            {row?.taskBegin}
            {row?.taskBegin && row?.taskEnd ? '~' : ''}
            {row?.taskEnd}
          </>
        ) : (
          <>长期有效</>
        )
    },
    {
      label: '回路开关分组',
      prop: 'taskGroupNames',
      minWidth: 200,
      showOverflowTooltip: true
    },
    {
      label: '更新时间',
      prop: 'updateTime',
      minWidth: 220,
      sortable: true
    },
    {
      label: '任务说明',
      prop: 'taskDesc',
      minWidth: 180,
      hidden: true,
      showOverflowTooltip: true
    },
    {
      label: '操作',
      prop: 'options',
      headerAlign: 'center',
      align: 'left',
      fixed: 'right',
      unFixed: true,
      disabled: true,
      minWidth: 310,
      render: ({ row }) => (
        <ElSpace wrap>
          {userState.permission.value.has('monitor_task_hardware_update') &&
            row.taskType &&
            row.taskType !== 2 && (
              <ElLink
                type="primary"
                icon={<AliIcon type="icon-bianji" />}
                onClick={() => {
                  if (row.taskType === 1) handleSetVisibleData('week', row)
                  if (row.taskType === 3) handleSetVisibleData('day', row)
                }}
              >
                编辑
              </ElLink>
            )}
          {userState.permission.value.has('monitor_task_hardware_apply') && (
            <ElLink
              type="primary"
              icon={<AliIcon type="icon-shebeiyingyong1" />}
              onClick={() => handleSetVisibleData('deviceApplication', row)}
            >
              设备应用
            </ElLink>
          )}
          {!!row.state && row.taskType !== 3 && (
            <ElLink
              type="primary"
              icon={<AliIcon type="icon-lishirenwu1" />}
              onClick={() => handleSetVisibleData('taskSchedule', row)}
            >
              任务时间表
            </ElLink>
          )}
          {userState.permission.value.has('monitor_task_hardware_remove') && (
            <ElLink
              type="primary"
              icon={<AliIcon type="icon-shanchu" />}
              onClick={() => handleDeleteSelectData(row)}
            >
              删除
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]

  return () => {
    // 周任务
    if (state.visible && state.visibleType === 'week') {
      return <WeeklyTasksComponent detail={state.record} goBack={handleClearVisibleData} />
    }
    // 设备应用
    if (state.visible && state.visibleType === 'deviceApplication') {
      return <DeviceApplicationComponent detail={state.record} goBack={handleClearVisibleData} />
    }
    // 列表 + 弹框
    return (
      <ElCard shadow="never" class="covered-with-content">
        <ProSaasTable<SwitchLightStrategyDataItemType>
          tableId="switchLightStrategy"
          ref={proSaasTableRef}
          columns={columns}
          rowKey="id"
          defaultSort={{ prop: 'updateTime', order: 'descending' }}
          dispatchType="switchLightStrategy/GetMonitoSwitchLightTaskList"
          headerTitle={
            userState.permission.value.has('monitor_task_hardware_add') && (
              <ElSpace>
                <ElButton type="primary" icon={Plus} onClick={() => handleSetVisibleData('week')}>
                  周设置任务
                </ElButton>
                <ElButton type="primary" icon={Plus} onClick={() => handleSetVisibleData('day')}>
                  全天任务
                </ElButton>
              </ElSpace>
            )
          }
          searchParams={{
            name: formValues.taskName && handleTrim(formValues.taskName)
          }}
          searchFormProps={{
            model: formValues
          }}
          searchformResponsiveCol={[
            <ElFormItem key="taskName" prop="taskName">
              <ElInput
                v-model={formValues.taskName}
                placeholder="任务名称"
                clearable
                onKeydown={handleKeyDownEnterSearchList}
              />
            </ElFormItem>,
            <ElFormItem key="taskType" prop="taskType">
              <ElSelect
                v-model={formValues.taskType}
                placeholder="请选择任务模式"
                clearable
                onChange={handleChangeValueActionSearchList}
              >
                {switchLightStrategyState.taskTypeSelectList.value?.map(
                  (item: TaskTypeEnumType) => (
                    <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey!} />
                  )
                )}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="state" prop="state">
              <ElSelect
                v-model={formValues.state}
                placeholder="请选择生效状态"
                clearable
                onChange={handleChangeValueActionSearchList}
              >
                {switchLightStrategyState.taskStateSelectList.value?.map(
                  (item: TaskStateEnumType) => (
                    <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey!} />
                  )
                )}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="groupId" prop="groupId">
              <ElSelect
                v-model={formValues.groupId}
                placeholder="请选择回路开关分组"
                filterable
                clearable
                onChange={handleChangeValueActionSearchList}
              >
                {loopSwitchGroupState.taskGroupHardwareSelectList.value?.map(
                  (item: LoopSwitchGroupDataItemType) =>
                    item?.id && (
                      <ElOption key={item?.id} label={item?.groupName} value={item?.id!} />
                    )
                )}
              </ElSelect>
            </ElFormItem>
          ]}
        />
        {state.visible && state.visibleType === 'day' && (
          <AllDayTasksModal detail={state.record} doClose={handleClearVisibleData} />
        )}
        {state.visible && state.visibleType === 'taskSchedule' && (
          <TaskScheduleModal detail={state.record} doClose={handleClearVisibleData} />
        )}
      </ElCard>
    )
  }
})
